package com.jwmp.rbac.web.servlet;

import com.jwmp.core.servlet.BaseServlet;
import com.jwmp.core.util.PageResult;
import com.jwmp.core.util.QueryObject;
import com.jwmp.core.util.QueryObjectUtil;
import com.jwmp.core.util.StringUtil;
import com.jwmp.rbac.domain.Department;
import com.jwmp.rbac.domain.Employee;
import com.jwmp.rbac.domain.Role;
import com.jwmp.rbac.service.IDepartmentService;
import com.jwmp.rbac.service.IEmployeeService;
import com.jwmp.rbac.service.impl.DepartmentServiceImpl;
import com.jwmp.rbac.service.impl.EmployeeServiceImpl;
import com.jwmp.rbac.util.SetPermission;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


@WebServlet("/employee/*")
public class EmployeeServlet extends BaseServlet {
    private IEmployeeService employeeService = new EmployeeServiceImpl();
    private IDepartmentService departmentService = new DepartmentServiceImpl();

    @SetPermission(moduleName = "员工管理",name="员工列表",expression = "/employee/list")
    public void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        QueryObject qo = QueryObjectUtil.req2qo(req);

        PageResult pageResult = employeeService.selectList(qo);
        req.setAttribute("pageResult",pageResult);
        req.getRequestDispatcher("/WEB-INF/views/rbac/employee_list.jsp").forward(req,resp);
    }

    // 启用和注销用户
    @SetPermission(moduleName = "员工管理",name="启用和注销员工",expression = "/employee/updateStatus")
    public void updateStatus(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String strId = req.getParameter("id");
        String strStatus = req.getParameter("status");
        if(StringUtil.hasLength(strId) && StringUtil.hasLength(strStatus)){
            employeeService.updateStatus(Long.valueOf(strId),Boolean.valueOf(strStatus));
        }
    }

    @SetPermission(moduleName = "员工管理",name="员工编辑页面",expression = "/employee/edit")
    public void edit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String strId = req.getParameter("id");

        if (StringUtil.hasLength(strId)) {
            Employee emp = employeeService.selectOne(Long.valueOf(strId));
            req.setAttribute("emp",emp);
        }

        List<Department> list = departmentService.selectList(new QueryObject(true),true).getList();
        req.setAttribute("departmentList",list);
        req.getRequestDispatcher("/WEB-INF/views/rbac/employee_input.jsp").forward(req,resp);
    }

    @SetPermission(moduleName = "员工管理",name="员工保存或修改",expression = "/employee/saveOrUpdate")
    public void saveOrUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Employee emp = new Employee();
        req2emp(req,emp);
        try {
            if (emp.getId() == null) {
                employeeService.insert(emp);
            }else{
                employeeService.update(emp);
            }
            list(req,resp);
        }catch (RuntimeException e){
            req.setAttribute("errorMsg",e.getMessage());
            req.getRequestDispatcher("/WEB-INF/views/rbac/employee_input.jsp").forward(req,resp);
        }
    }

    @SetPermission(moduleName = "员工管理",name="绑定角色页面",expression = "/employee/bindRoleEdit")
    public void bindRoleEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String strId = req.getParameter("id");
        if (StringUtil.hasLength(strId)) {
            // 获取所有该用户没有的角色
            List<Role> roleListNotInEmpId= employeeService.selectRoleNotInEmpId(Long.valueOf(strId));
            // 获取所有该用户存在的角色
            List<Role> roleListByEmpId = employeeService.selectRoleByEmpId(Long.valueOf(strId));
            Employee emp = employeeService.selectOne(Long.valueOf(strId));

            req.setAttribute("roleListNotInEmpId",roleListNotInEmpId);
            req.setAttribute("roleListByEmpId",roleListByEmpId);
            req.setAttribute("emp",emp);
        }
        req.getRequestDispatcher("/WEB-INF/views/rbac/employee-role.jsp").forward(req,resp);
    }

    @SetPermission(moduleName = "员工管理",name="绑定角色",expression = "/employee/bindRole")
    public void bindRole(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String strId = req.getParameter("id");
        String[] roleIds = req.getParameterValues("roleId");
        if (StringUtil.hasLength(strId)) {
            List<Long> roleIdList = roleIds != null
                                ? Arrays.stream(roleIds).map(strRoleId -> Long.valueOf(strRoleId)).collect(Collectors.toList())
                                : new ArrayList<Long>();
            employeeService.bindRole(Long.valueOf(strId),roleIdList);
        }

        bindRoleEdit(req,resp);
    }


    private void req2emp(HttpServletRequest req, Employee emp) {
        String strId = req.getParameter("id");
        if (StringUtil.hasLength(strId)) {
            emp.setId(Long.valueOf(strId));
        }

        String username = req.getParameter("username");
        emp.setUsername(username);
        String password = req.getParameter("password");
        emp.setPassword(password);
        String name = req.getParameter("name");
        emp.setName(name);
        String email = req.getParameter("email");
        emp.setEmail(email);
        String strAge = req.getParameter("age");
        if (StringUtil.hasLength(strAge)) {
            emp.setAge(Integer.valueOf(strAge));
        }
        String strHiredate = req.getParameter("hiredate");
        if (StringUtil.hasLength(strHiredate)) {
            try {
                Date date = new SimpleDateFormat("yyyy-MM-dd").parse(strHiredate);
                emp.setHiredate(date);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        String strAdmin = req.getParameter("admin");
        if (StringUtil.hasLength(strAdmin)) {
            emp.setAdmin(Boolean.valueOf(strAdmin));
        }
        String strDeptId = req.getParameter("deptId");
        if (StringUtil.hasLength(strDeptId)) {
            Department dept = new Department();
            dept.setId(Long.valueOf(strDeptId));
            emp.setDept(dept);
        }
    }
}














